import _ from 'lodash'
import * as tableRender from './tableRender'
import ApiHCombox from '../../api'
/**
 * 动态表单组件转换
 * @param {Array} tags 后端数据
 */
export const dynamicFormItem = tags => {
  let items = []
  tags.forEach(element => {
    let item = {
      key: element.property,
      label: element.lable,
      type: element.tagType,
      select: {
        readMethod: () => {
          return ApiHCombox.findSelectItemListByCategory(element.listCategory)
        },
      },
      daterange: { startKey: element.property, endKey: element.endProperty },
    }
    items.push(item)
  })
  return items
}

export const dynamicColumn = (columns, navigateTo) => {
  let list = []
  columns.forEach(element => {
    let width = _.parseInt(element.width)
    let column = { key: element.field, title: element.title, format: element.format, expands: element.expands }
    if (!isNaN(width)) {
      column.width = width
    }
    if (element.field === 'entityNumber' && navigateTo) {
      column.render = (h, params) => {
        return tableRender.workflowNumberCell(h, params, () => {
          navigateTo(params)
        })
      }
    }
    list.push(column)
  })
  return list
}

export const formatColumn = column => {
  if (column.format) {
    switch (column.format) {
      case 'amount':
        column.render = (h, params) => {
          return tableRender.priceCell(h, params.row[column.key])
        }
        break
      case 'yorn':
        column.render = (h, params) => {
          return tableRender.booleanCell(h, params.row[column.key])
        }
        break
      case 'html':
        column.render = (h, params) => {
          return h('div', { domProps: { innerHTML: params.row[column.key] } })
        }
        break
    }
  }
  if (!column.render && column.expands) {
    column.render = (h, params) => {
      return h('div', genFields(h, column.expands, params))
    }
  }
}

const genFields = (h, expands, params) => {
  let fields = []
  expands.forEach(fld => {
    const value = _.get(params.row, fld.key) || ''
    if (_.trim(fld.title).length <= 0) {
      fields.push(h('p', value))
    } else {
      fields.push(h('p', `${fld.title}: ${value}`))
    }
  })
  return fields
}
